<?php
namespace app\common\model;
use x\Xbase;
class UserUpgrade extends Xbase
{


    /**
     * 同步第三方openid，即临时推荐关系
     * @param  integer $type      [description]
     * @param  [type]  $openid    [description]
     * @param  [type]  $s_user_id [description]
     * @param  [type]  $s_openid  [description]
     * @return [type]             [description]
     */
    public function add($user_id,$level_id,$pay_type,$user_sign=""){
        $userinfo = $this->db->find("user",$user_id);
        if(!$userinfo){
            return $this->setError('用户不存在或被禁用');
        }
        $levelinfo = $this->db->find("user_level_config",$user_id);
        if(!$levelinfo){
            return $this->setError('未配置的级别');
        }
        if($userinfo['level'] >= $levelinfo["level"]){
            return $this->setError('只能升到比你大的级别');
        }
        $pay_money =  0;
        if(bcmul($userinfo['money'],100) < bcmul($levelinfo["money"],100)){
            $pay_money = bcmul($levelinfo["money"],100) - bcmul($userinfo['money'],100);
        }
        $order_no = com_order_no();
        $data = [
            "user_id" => $user_id,
            "order_no" => $order_no,
            "level" => $levelinfo["level"],
            "money" => $levelinfo["money"],
            "pay_money" => $pay_money,
            "stock" => $levelinfo["stock"],
            "user_sign" => $user_sign,
            "pay_type" => $pay_type,
            "create_time" => time(),
        ];
        $rs = $this->db->insert("user_upgrade",$data);
        if(!$rs){
            $this->setError('生成订单失败');
            return false;
        }
        return $data;
    }

}
